import { SearchOutlined } from '@ant-design/icons'
import { Button, Form, Input, message, Modal, Popconfirm, Space, Spin, Table } from 'antd'
import React, { useEffect, useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router'

import ArticleDisplay from '@/components/ArticleDisplay'
import useArticleStore from '@/stores/articleStore'
import { dayjs } from '@/utils/dayjs'

import type { ArticleMetaItem } from '../../types'

// ======================= 资源共享与文章管理复用说明 =====================
// 本文件可以通过路由区分“文章管理”与“资源共享”模块。当前路由若以 /resource 开头，则列表仅展示 type=RESOURCE 的资源文章，否则展示普通文章。
// 该策略复用了全部UI逻辑与数据操作，仅依赖type进行业务数据的隔离，便于后期维护与拓展。
// ====================================================================
const ArticleManagement: React.FC = () => {
  // Router hooks
  const navigate = useNavigate()
  const location = useLocation()
  // 判断当前路径是否为资源文章模式（RESOURCE，对应资源共享模块）
  const isResourceMode = location.pathname.startsWith('/resource')

  // Store 取值
  const articles = useArticleStore(state => state.articles)
  const total = useArticleStore(state => state.total)
  const currentPage = useArticleStore(state => state.currentPage)
  const pageSize = useArticleStore(state => state.pageSize)
  const loading = useArticleStore(state => state.loading)
  const getArticleList = useArticleStore(state => state.getArticleList)
  const handleSearch = useArticleStore(state => state.handleSearch)
  const resetSearch = useArticleStore(state => state.resetSearch)
  const handlePageChange = useArticleStore(state => state.handlePageChange)
  const deleteArticle = useArticleStore(state => state.deleteArticle)
  const previewArticles = useArticleStore(state => state.previewArticles)
  const previewLoading = useArticleStore(state => state.previewLoading)
  const getArticleDetailsByIds = useArticleStore(state => state.getArticleDetailsByIds)

  // Form表单管理搜索
  const [searchForm] = Form.useForm()

  // 资源文章预览Modal状态
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewId, setPreviewId] = useState<string | null>(null)

  // useEffect
  useEffect(() => {
    // 页面首次加载或模式切换（文章/资源）时，自动按当前模式type查询数据
    getArticleList(1, 10, '', isResourceMode ? 'RESOURCE' : 'NORMAL')
  }, [isResourceMode])

  // useMemo - 派生变量
  const columns = useMemo(
    () => [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title'
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '操作',
        key: 'action',
        render: (_: unknown, record: ArticleMetaItem) => (
          <Space>
            {/* 资源共享模块下展示“查看”按钮，点击弹出预览Modal */}
            {isResourceMode && (
              <Button
                type="default"
                onClick={() => {
                  setPreviewId(record.id)
                  setPreviewVisible(true)
                  // 打开Modal时根据ID拉取文章详情用于预览
                  getArticleDetailsByIds([record.id])
                }}
              >
                查看
              </Button>
            )}
            <Button
              color="primary"
              variant="outlined"
              onClick={() =>
                navigate(`${isResourceMode ? '/resource/modify/' : '/article/modify/'}${record.id}`)
              }
            >
              编辑
            </Button>
            <Popconfirm
              title="确定要删除这篇文章吗？"
              description={
                <span>
                  此操作不可恢复，请谨慎操作。
                  <br />
                  <span style={{ color: '#1890ff', fontWeight: 'bold' }}>
                    将被删除：文章《{record.title}》
                  </span>
                </span>
              }
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                color="danger"
                variant="outlined"
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        )
      }
    ],
    [navigate, isResourceMode]
  )

  // 方法定义
  const handleSearchSubmit = () => {
    searchForm.validateFields().then(values => {
      // 搜索、重置等行为，全部根据模式type设置参数，确保数据隔离
      handleSearch(values.title || '', isResourceMode ? 'RESOURCE' : 'NORMAL')
    })
  }

  const handleResetSearch = () => {
    searchForm.resetFields()
    resetSearch(isResourceMode ? 'RESOURCE' : 'NORMAL')
  }

  const handleDelete = async (id: string) => {
    const success = await deleteArticle(id)
    if (success) {
      message.success('文章删除成功')
    }
  }

  return (
    <div className="w-full max-w-full">
      <div className="mb-4 flex justify-between">
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearchSubmit}
        >
          <Form.Item name="title">
            <Input
              placeholder="请输入标题搜索"
              allowClear
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
              >
                搜索
              </Button>
              <Button onClick={handleResetSearch}>清空</Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      {/* 资源文章预览Modal，仅在资源模式使用 */}
      <Modal
        title="查看文章"
        open={previewVisible}
        onCancel={() => {
          setPreviewVisible(false)
          setPreviewId(null)
        }}
        footer={null}
        width={1300}
        destroyOnHidden
      >
        {previewId && (
          <Spin spinning={previewLoading}>
            <ArticleDisplay articles={previewArticles} />
          </Spin>
        )}
      </Modal>
      <Table
        columns={columns}
        dataSource={articles}
        rowKey="id"
        pagination={{
          total,
          current: currentPage,
          pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: total => `共 ${total} 条`,
          onChange: handlePageChange,
          onShowSizeChange: (current, size) => handlePageChange(current, size)
        }}
        loading={loading}
      />
    </div>
  )
}

export default ArticleManagement
